package com.efounder.chat.fragment;

import android.annotation.SuppressLint;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.Nullable;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.form.application.ApplicationContainer;
import com.efounder.form.application.FormApplication;
import com.efounder.form.application.FormViewContainer;
import com.efounder.form.application.util.Form;
import com.efounder.form.application.util.FormAppUtil;
import com.efounder.frame.ViewSize;
import com.efounder.frame.arcmenu.ArcMenu;
import com.efounder.frame.baseui.EFFragment;
import com.efounder.frame.fragment.EFAppAccountTabFragmentInterface;
import com.efounder.frame.utils.EFAppAccountUtils;
import com.efounder.frame.xmlparse.EFAppAccountRegistry;
import com.efounder.frame.xmlparse.EFXmlConstants;
import com.efounder.mobilemanager.R;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by hudq on 2016/8/29. xx
 * 处理多个表单，用此类{区别于 @link EFAppAccountFormFragment}
 */

public class EFAppAccountFormListFragment_noThread extends EFFragment{
    private int position;
    private List<StubObject> stubList;
    private StubObject currentStub;

    public static EFAppAccountFormListFragment_noThread newInstance(int position, ArrayList<StubObject> stubList){
        EFAppAccountFormListFragment_noThread appAccountFragment = new EFAppAccountFormListFragment_noThread();
        Bundle bundle = new Bundle();
        bundle.putInt("position",position);
        bundle.putSerializable("stubList", stubList);
        appAccountFragment.setArguments(bundle);
        return appAccountFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        position = getArguments().getInt("position");
        stubList = (List<StubObject>) getArguments().getSerializable("stubList");
        currentStub = stubList.get(position);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.ef_fragment_app_account_form,container,false);
        TextView textView = (TextView) view.findViewById(R.id.textView_test);
        textView.setText(position+"--" + stubList.get(position).getCaption() +"--"+ stubList.get(position).getString(EFXmlConstants.ATTR_FORM,""));

        final LinearLayout ll = (LinearLayout) view.findViewById(R.id.rootLayout);

        ll.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            @SuppressWarnings("deprecation")
            @SuppressLint("NewApi")
            public void onGlobalLayout() {

                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                    ll.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                } else {
                    ll.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
                //1.判断是否初始化所有Form
                StubObject parentStub = EFAppAccountRegistry.getStubByID(currentStub.getString(EFAppAccountRegistry.ATTR_PARENT_ID,""));
                boolean isInitAllForm = parentStub.getString(EFXmlConstants.ATTR_IS_INIT_ALL_FORM,"0").equals("1");
                String parentID = (String) parentStub.getID();
                if (isInitAllForm){
                    //2.如果内存中没有applicationContainer就生成（可能被回收了）
                    ApplicationContainer applicationContainer = EFAppAccountUtils.applicationContainerMap.get(parentID);
                    if (applicationContainer == null){
                        applicationContainer = generateAllForms(ll);
                        EFAppAccountTabFragmentInterface tabFragmentInterface = (EFAppAccountTabFragmentInterface) getParentFragment();
                        ArcMenu arcMenu = tabFragmentInterface.getArcMenu();
                        //TODO 根据购物车中已有的数据恢复角标
//                  item.superscriptAddNumber(66);
                        applicationContainer.putObject("arcMenu",arcMenu);
                        EFAppAccountUtils.applicationContainerMap.put(parentID,applicationContainer);
                    }
                    //添加当前Form
                    addCurrentForm(ll,applicationContainer);
                }else {
                    addForm(ll);
                }
            }

        });

        return view;
    }

    private void addForm(LinearLayout ll ) {
        String xmlName = stubList.get(position).getString(EFXmlConstants.ATTR_FORM,"");
        String formPath = EFAppAccountUtils.getAppAccountFormPath() + "/" + xmlName;
        try {
            InputStream inputStream =  new FileInputStream(formPath);
            ViewSize viewSize = new ViewSize(ll.getMeasuredWidth(),ll.getMeasuredHeight());
            Form form = new Form();
            form.setFormName(xmlName.substring(0,xmlName.indexOf(".xml")));
            form.setInputStream(inputStream);
            form.setViewSize(viewSize);

            ApplicationContainer applicationContainer = FormAppUtil.generateForm(form);
            FormApplication formApplication = applicationContainer.getFormApplication(xmlName.substring(0,xmlName.indexOf(".xml")));
            FormViewContainer formViewContainer = (FormViewContainer) formApplication.getFormContainer("form1");
            if (formViewContainer != null){
                ll.removeAllViews();
                ll.addView(formViewContainer);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }

    private ApplicationContainer generateAllForms(LinearLayout ll){
        List<Form> formList = new ArrayList();
        ViewSize viewSize = new ViewSize(ll.getMeasuredWidth(),ll.getMeasuredHeight());
        for (int i=0; i<stubList.size(); i++) {
            StubObject stub = stubList.get(i);
            //1.form
            String formName = stub.getString(EFXmlConstants.ATTR_FORM,"");
            String formPath = EFAppAccountUtils.getAppAccountFormPath() + "/" + formName;
            String formID = stub.getString(EFXmlConstants.ATTR_FORM_ID,"");
            try {
                InputStream inputStream =  new FileInputStream(formPath);
                Form form = new Form();
                form.setFormName(formID);
                form.setInputStream(inputStream);
                form.setViewSize(viewSize);
                formList.add(form);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            //2.attachForm(例如：购物车form)
            int bottomTabBarHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,50,getResources().getDisplayMetrics());
            ViewSize attachViewSize = new ViewSize(ll.getMeasuredWidth(),ll.getMeasuredHeight() + bottomTabBarHeight);
            String attachFormName = stub.getString(EFXmlConstants.ATTR_ATTACH_FORM,"");
            if (!"".equals(attachFormName)){
                String attachFormPath = EFAppAccountUtils.getAppAccountFormPath() + "/" + attachFormName;
                String attachFormID = stub.getString(EFXmlConstants.ATTR_ATTACH_FORM_ID,"");
                try {
                    InputStream inputStream =  new FileInputStream(attachFormPath);
                    Form form = new Form();
                    form.setFormName(attachFormID);
                    form.setInputStream(inputStream);
                    form.setViewSize(attachViewSize);
                    formList.add(form);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }

        }

//        String attachFormName = "shopping.xml";
//        if (!"".equals(attachFormName)){
//            String attachFormPath = EFAppAccountUtils.getAppAccountFormPath() + "/" + attachFormName;
//            String attachFormID = "shopping";
//            try {
//                InputStream inputStream =  new FileInputStream(attachFormPath);
//                Form form = new Form();
//                form.setFormName(attachFormID);
//                form.setInputStream(inputStream);
//                form.setViewSize(viewSize);
//                formList.add(form);
//            } catch (FileNotFoundException e) {
//                e.printStackTrace();
//            }
//        }

        return FormAppUtil.generateForm(formList);
    }

    private void addCurrentForm(LinearLayout ll ,ApplicationContainer applicationContainer) {
        String formID = currentStub.getString(EFXmlConstants.ATTR_FORM_ID,"");
        FormApplication formApplication = applicationContainer.getFormApplication(formID);
        if (formApplication != null){
            FormViewContainer formViewContainer = (FormViewContainer) formApplication.getFormContainer("form1");
            if (formViewContainer == null) {
                Log.e("ee","没有找到名称为form1的表单");
                return;
            }
            ViewGroup parent = (ViewGroup) formViewContainer.getParent();
            if (parent != null){
                parent.removeView(formViewContainer);
            }

            ll.removeAllViews();
            ll.addView(formViewContainer);
        }
    }

}
